package com.yuntsg.nnsfcp.service.back.loginhold;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 利用 持久化 session 做后台的常登陆
 * 有效时长 1 个月
 *
 * @author ：ljx
 * @date ：Created in 2019/12/13  17:15
 */
public class LoginHoldService {

    /**
     * 添加 用户在线
     *
     * @param request
     */
    public static void loginHold(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(2419200);

        // 浏览器cookie存储
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        ///cookie.setDomain("202.116.13.235");
        cookie.setDomain("yuntsg.com");
        // 2419200秒 一个月
        cookie.setMaxAge(2419200);
        response.addCookie(cookie);
    }

    /**
     * 销毁
     *
     * @param request
     */
    public static void backLogOut(HttpServletRequest request, HttpServletResponse response) {

        request.getSession().invalidate();

        // 删除cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("JSESSIONID".equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    ///cookie.setDomain("202.116.13.235");
                    cookie.setDomain("yuntsg.com");
                    response.addCookie(cookie);
                }
            }
        }
    }


}
